package com.feihong.yw189.global;

import android.text.TextUtils;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Sabirjan on 2018/04/26.
 * TXGW.
 * 飞宏电子
 */
public class RequestTools {

    private static Map<String, List<Callback.Cancelable>> mRequestMap;

    static {
        mRequestMap = new HashMap<>();
    }

    /***
     * 请求添加到集合里
     * @param activityName
     * @param cancelable
     * @return
     */
    public static boolean addNewRequest(String activityName, Callback.Cancelable cancelable) {
        try {
            if (TextUtils.isEmpty(activityName) || cancelable == null || cancelable.isCancelled()) {
                return false;
            }
            if (mRequestMap == null) {
                mRequestMap = new HashMap<>();
            }
            if (mRequestMap.containsKey(activityName)) {
                List<Callback.Cancelable> items = mRequestMap.get(activityName);
                items.add(cancelable);
                mRequestMap.put(activityName, items);
            } else {
                List<Callback.Cancelable> items = new ArrayList<>();
                items.add(cancelable);
                mRequestMap.put(activityName, items);
            }
            return true;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 取消集合里面的请求
     *
     * @param activityName
     * @return
     */
    public static boolean removeRequest(String activityName) {
        try {
            if (TextUtils.isEmpty(activityName)) {
                return false;
            }
            if (mRequestMap == null) {
                mRequestMap = new HashMap<>();
            }
            if (mRequestMap.containsKey(activityName)) {
                List<Callback.Cancelable> items = mRequestMap.get(activityName);
                if (items == null) {
                    return true;
                }
                for (int i = 0, len = items.size(); i < len; i++) {
                    if (items.get(i) != null && !items.get(i).isCancelled()) {
                        try {
                            items.get(i).cancel();
                        } catch (Exception ex) {
                        }
                    }
                }
                items.clear();
                mRequestMap.remove(activityName);
            }
            return true;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

}
